package dao

import (
	"context"
	"fmt"

	"bmember/internal/object"
	"bmember/pkg/util"

	"bmember/internal/model"
)

// IntegralLogDao 积分记录
type IntegralLogDao interface {
	// CreateIntegralLog 创建积分记录
	CreateIntegralLog(ctx context.Context, iLog *model.IntegralLog) (int64, error)
	// GetIntegralsByMembersGroup 加载积分记录
	GetIntegralsByMembersGroup(ctx context.Context, memberIds []int64, groupId int64, pg object.Pagination) ([]*model.IntegralLog, uint32, error)
	// GetIntegralLogByOrder 根据单号获取积分记录
	GetIntegralLogByOrder(ctx context.Context, orderNo string) ([]*model.IntegralLog, error)
}

type iLogDaoImpl struct {
	*DaoBase
	name string
}

var iLogDao IntegralLogDao

// InitIntegralLogDao 初始化 account log
func InitIntegralLogDao() {
	iLogDao = &iLogDaoImpl{
		DaoBase: daoBase,
		name:    "dao_integral_log",
	}
}

// GetIntegralLogDao 获取句柄
func GetIntegralLogDao() IntegralLogDao {
	return iLogDao
}

// CreateIntegralLog 创建积分记录
func (dao *iLogDaoImpl) CreateIntegralLog(ctx context.Context, iLog *model.IntegralLog) (int64, error) {
	if iLog == nil {
		return 0, nil
	}
	param := []interface{}{
		iLog.BrandId,
		iLog.StoreId,
		iLog.GroupId,
		iLog.CardId,
		iLog.MemberId,
		iLog.AccId,
		iLog.IntType,
		iLog.Num,
		iLog.PayOrderNo,
		iLog.RefundOrderNo,
		iLog.Amount,
		iLog.EmpId,
		iLog.Remark,
	}
	query := "INSERT INTO integral_log (brand_id, store_id, group_id, card_id, member_id, acc_id, int_type, num, " +
		"pay_order_no, refund_order_no, amount, emp_id, remark, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())"
	aff, err := dao.db.PgExec(ctx, "id", query, param...)
	if err != nil {
		return 0, err
	}
	lastId, _ := aff.GetLastId()
	return lastId, nil
}

// GetIntegralsByMembersGroup 加载积分记录
func (dao *iLogDaoImpl) GetIntegralsByMembersGroup(ctx context.Context, memberIds []int64, groupId int64, pg object.Pagination) ([]*model.IntegralLog, uint32, error) {
	if len(memberIds) == 0 {
		return nil, 0, nil
	}
	where := fmt.Sprintf("FROM integral_log WHERE member_id IN (%s) AND group_id=%d AND deleted_at=0 ", util.SqlIDsJoin(memberIds), groupId)
	total, err := dao.CountNum(ctx, where)
	if err != nil {
		return nil, 0, err
	}
	query := fmt.Sprintf("SELECT id, brand_id, group_id, member_id, int_type, num, created_at %s ORDER BY created_at DESC %s", where, pg.GetDbOffset())
	var iLogs []*model.IntegralLog
	err = dao.db.Query(ctx, &iLogs, query)
	return iLogs, total, err
}

// GetIntegralLogByOrder 根据单号获取积分记录
func (dao *iLogDaoImpl) GetIntegralLogByOrder(ctx context.Context, orderNo string) ([]*model.IntegralLog, error) {
	query := "SELECT id, brand_id, group_id, member_id, int_type, num FROM integral_log WHERE pay_order_no=? AND deleted_at=0"
	var iLogs []*model.IntegralLog
	err := dao.db.Query(ctx, &iLogs, query, orderNo)
	return iLogs, err
}
